//
//  WJAppUtil.m
//  Imagedemo
//
//  Created by 文杰 许                       on 2018/4/4.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

#import "WJAppUtil.h"


@implementation WJAppUtil
//发短信
+ (void)messageTo:(NSString *)number
{
    NSString *url=[NSString stringWithFormat:@"sms://%@",number];
    
    [self openURL:url];
}


//打电话
+ (void)dialTo:(NSString *)number
{
    NSString *url=[NSString stringWithFormat:@"telprompt://%@",number];
    
    [self openURL:url];
}


//发送邮件
+ (void)mailTo:(NSString *)address
{
    NSString *url=[NSString stringWithFormat:@"mailto://%@",address];
    
    [self openURL:url];
}


//打开URL(网页或地图)
+ (void)browseURL:(NSString *)URL
{
    URL=[URL stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    URL=[NSString stringWithFormat:@"http://%@",URL];
    
    [self openURL:URL];
}


//打开应用商店
+ (void)viewApp:(NSString *)appID
{
    NSString *url=[NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@",appID];
    
    [self openURL:url];
}


//打开应用评分
+ (void)rateApp:(NSString *)appID
{
    if (@available(iOS 10.3, *))
    {
        if([SKStoreReviewController respondsToSelector:@selector(requestReview)])
        {
            [SKStoreReviewController requestReview];
        }
        else
        {
            NSString *url=[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review",appID];
            
            [self openURL:url];
        }
    }
    else
    {
        NSString *url=[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review",appID];
        
        [self openURL:url];
    }
}


//设置app
+ (void)goToAppSetting
{
    NSString *url=UIApplicationOpenSettingsURLString;
    
    [self openURL:url];
}


//设置iCloud
+ (void)goToCloudSetting
{
    NSString *url=@"prefs:root=CASTLE";
    
    [self openURL:url];
}


//设置定位
+ (void)goToLocationSetting
{
    NSString *url=@"prefs:root=LOCATION_SERVICES";
    
    [self openURL:url];
}


//设置通知
+ (void)goToNotificationSetting
{
    NSString *url=@"prefs:root=NOTIFICATIONS_ID";
    
    [self openURL:url];
}


///设置Wi-Fi
+ (void)goToWifiSetting
{
    NSString *url=@"prefs:root=WIFI";
    
    [self openURL:url];
}


//打开app
+ (void)openApp:(NSString *)app withMessage:(NSString *)msg
{
    NSString *url=[NSString stringWithFormat:@"%@://%@",app,msg];
    
    [self openURL:url];
}


//打开URL
+ (void)openURL:(NSString *)URL
{
    //注意url中包含协议名称，iOS根据协议确定调用哪个应用，例如发送邮件是“sms://”其中“//”可以省略写成“sms:”(其他协议也是如此)
    NSURL *url=[NSURL URLWithString:URL];
    
    //    UIApplication *application=[UIApplication sharedApplication];
    //
    //    if(![application canOpenURL:url])//白名单才能返回YES
    //    {
    //        NSLog(@"can not open url:%@",url);
    //
    //        return;
    //    }
    //    else
    {
        [[UIApplication sharedApplication] openURL:url];
    }
}


//获取主窗口
+ (UIWindow *)keyWindow
{
    return [UIApplication sharedApplication].keyWindow;
}


//获取根视图
+ (UIView *)rootViewFromView:(UIView *)view
{
    if(view)
    {
        UIView *rootView=view;
        
        while(rootView.superview)
        {
            if([rootView.superview isKindOfClass:[UIWindow class]])
            {
                break;
            }
            
            rootView=rootView.superview;
        }
        
        return rootView;
    }
    else
    {
        return [self keyWindow];
    }
}


//获取当前的视图控制器
+ (UIViewController *)currentViewController
{
    UIViewController *currentVC=nil;
    
    UIWindow *window=[[UIApplication sharedApplication] keyWindow];
    
    if(window.windowLevel!=UIWindowLevelNormal)
    {
        NSArray *windows=[[UIApplication sharedApplication] windows];
        
        for(UIWindow * tmpWin in windows)
        {
            if(tmpWin.windowLevel==UIWindowLevelNormal)
            {
                window=tmpWin;
                
                break;
            }
        }
    }
    
    
    UIView *frontView=[[window subviews] objectAtIndex:0];
    
    id nextResponder=[frontView nextResponder];
    
    if([nextResponder isKindOfClass:[UIViewController class]])
    {
        currentVC=nextResponder;
    }
    else
    {
        currentVC=window.rootViewController;
    }
    
    
    return currentVC;
}


//获取顶层的视图控制器
+ (UIViewController *)topViewController
{
    UIViewController *topVC=nil;
    
    topVC=[self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    
    while(topVC.presentedViewController)
    {
        topVC=[self _topViewController:topVC.presentedViewController];
    }
    
    return topVC;
}


//获取顶层视图控制器的内部递归方法
+ (UIViewController *)_topViewController:(UIViewController *)vc
{
    if([vc isKindOfClass:[UINavigationController class]])
    {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    }
    else if ([vc isKindOfClass:[UITabBarController class]])
    {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    }
    else
    {
        return vc;
    }
    
    return nil;
}


//获取view所在的视图控制器
+ (UIViewController *)controllerWithView:(UIView *)view
{
    for(UIView* next=[view superview];next;next=next.superview)
    {
        UIResponder* nextResponder=[next nextResponder];
        
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)nextResponder;
        }
    }
    
    return nil;
}


//获取View相对于某个控件的frame
+ (CGRect)frameInOther:(UIView *)other fromView:(UIView *)view
{
    return [view.superview convertRect:view.frame toView:other];
}


//获取View相对keyWindow的frame
+ (CGRect)frameInWindowFromView:(UIView *)view
{
    if(view)
    {
        return [view.superview convertRect:view.frame toView:[self keyWindow]];
    }
    else
    {
        return CGRectZero;
    }
}


//获取屏幕尺寸
+ (CGSize)screenSize
{
    return [[UIScreen mainScreen] bounds].size;
}


//获取屏幕缩放比率
+ (float)screenScale
{
    return [UIScreen mainScreen].scale;
}


//获取状态栏尺寸
+ (CGSize)statusBarSize
{
    return [UIApplication sharedApplication].statusBarFrame.size;
}


//设置网络活动指示器
+ (void)setNetworkStateActive:(BOOL)active
{
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:active];//显示状态栏的网络活动指示器
                   });
}


//设置状态栏隐藏
+ (void)setStatusBarHidden:(BOOL)hidden withAnimation:(BOOL)animation
{
    if (@available(iOS 9.0, *))
    {
        [[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animation];
    }
    
}


//设置状态栏亮色
+ (void)setStatusBarLightStyle
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}


//设置状态栏暗色
+ (void)setStatusBarDarkStyle
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}


//获取状态栏是否亮色
+ (BOOL)isStatusBarLightStyle
{
    return [[UIApplication sharedApplication] statusBarStyle]==UIStatusBarStyleLightContent;
}


//显示状态栏
+ (void)showStatusBar
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
}


//隐藏状态栏
+ (void)hideStatusBar
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
}


//获取文档路径
+ (NSString *)docPath
{
    return [NSString stringWithFormat:@"%@/Documents",[WJSystemInfo systemInfo].homePath];
}


//获取app路径
+ (NSString *)appPath
{
    return [WJSystemInfo systemInfo].appPath;
}


//获取临时文件路径
+ (NSString *)tempPath
{
    return [WJSystemInfo systemInfo].tmpPath;
}


//获取启动图片
+ (UIImage *)launchImage
{
    UIImage *lauchImage=nil;
    NSString *viewOrientation=nil;//方向
    CGSize viewSize=[UIScreen mainScreen].bounds.size;
    
    UIInterfaceOrientation orientation=[[UIApplication sharedApplication] statusBarOrientation];
    
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight)
    {
        viewOrientation=@"Landscape";
    }
    else
    {
        viewOrientation=@"Portrait";
    }
    
    NSArray *imagesDictionary=[[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    
    for(NSDictionary *dict in imagesDictionary)
    {
        CGSize imageSize=CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if((CGSizeEqualToSize(imageSize, viewSize) || (imageSize.width==viewSize.height && imageSize.height==viewSize.width)) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            lauchImage=[UIImage imageNamed:dict[@"UILaunchImageName"]];
        }
    }
    
    return lauchImage;
}


//获取竖屏方向的启动图片
+ (UIImage *)portraitLaunchImage
{
    UIImage *lauchImage=nil;
    NSString *viewOrientation=@"Portrait";//方向
    CGSize viewSize=[UIScreen mainScreen].bounds.size;
    
    NSArray *imagesDictionary=[[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    
    for(NSDictionary *dict in imagesDictionary)
    {
        CGSize imageSize=CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if((CGSizeEqualToSize(imageSize, viewSize) || (imageSize.width==viewSize.height && imageSize.height==viewSize.width)) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            lauchImage=[UIImage imageNamed:dict[@"UILaunchImageName"]];
        }
    }
    
    return lauchImage;
}


//获取横屏方向的启动图片
+ (UIImage *)landscapeLaunchImage
{
    UIImage *lauchImage=nil;
    NSString *viewOrientation=@"Landscape";//方向
    CGSize viewSize=[UIScreen mainScreen].bounds.size;
    
    NSArray *imagesDictionary=[[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    
    for(NSDictionary *dict in imagesDictionary)
    {
        CGSize imageSize=CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if(CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            lauchImage=[UIImage imageNamed:dict[@"UILaunchImageName"]];
        }
    }
    
    return lauchImage;
}

//获取系统版本
+ (NSString *)OSVersion
{
    return [WJSystemInfo systemInfo].osVersion;
}


//获取app版本
+ (NSString *)appVersion
{
    return [WJSystemInfo systemInfo].appVersion;
}


//获取系统语言
+ (int)language
{
    return [WJSystemInfo systemInfo].languageID;
}

//修复无法播放声音的问题
+ (void)repairAudioPlayer
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}


//设置应用图标徽标数字
+ (void)setBadgeNumber:(long)badge
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
}


//获取当前应用图标徽标数字
+ (long)getBadgeNumber
{
    return [[UIApplication sharedApplication] applicationIconBadgeNumber];
}


//切换屏幕方向
+ (BOOL)setOrientation:(UIInterfaceOrientation)orientation
{
    if([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
    {
        SEL selector=NSSelectorFromString(@"setOrientation:");
        
        NSInvocation *invocation=[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        
        int val=orientation;
        [invocation setArgument:&val atIndex:2];
        
        [invocation invoke];
        
        return YES;
    }
    
    return NO;
}


//获取当前的屏幕方向
+ (UIDeviceOrientation)currentOrientation
{
    return [UIDevice currentDevice].orientation;
}


//设置禁止自动锁屏
+ (void)setAutoLockScreenDisabled:(BOOL)disabled
{
    [[UIApplication sharedApplication] setIdleTimerDisabled:disabled];
}
@end
